import 'dart:convert';

import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/user_details_by_userI_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/page/login_page.dart';
import 'package:elephant_fish/page/user_personal_interface_page.dart';
import 'package:elephant_fish/tencentImPlugin/common/colors.dart';
import 'package:elephant_fish/tencentImPlugin/pages/conversationInfo/conversationInfo.dart';
import 'package:elephant_fish/tencentImPlugin/pages/userProfile/userProfile.dart';
import 'package:elephant_fish/tencentImPlugin/provider/currentMessageList.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';

import 'component/conversationInner.dart';
import 'component/msgInput.dart';


class Conversion extends StatefulWidget {
  Conversion(this.conversationID,{this.userId});
  final String conversationID;
  final String userId;
  @override
  State<StatefulWidget> createState() => ConversionState(conversationID);
}

class ConversionState extends State<Conversion> {
  String conversationID;
  int type = 1;
  String lastMessageId = '';
  String userID ;
  String groupID;
  UserInfoEntity userInfoEntity;
  List<V2TimMessage> msgList = List.empty(growable: true);
  V2TimValueCallback<List<V2TimUserFullInfo>> infos;
  V2TimValueCallback<List<V2TimGroupInfoResult>> groups;
  Icon righTopIcon;
  bool isreverse = true;
  List<V2TimMessage> currentMessageList = List.empty(growable: true);
  ConversionState(this.conversationID);

  void initState() {
    super.initState();
    getUserInfo();
    getUserInfos();
    getConversion();
  }

  openProfile(context) {
    String userId = type == 1 ? widget.userId : groupID;
    String id = type == 1 ? widget.userId : groupID;
    Navigator.push(
      context,
      new MaterialPageRoute(
        builder: (context) =>
            // type == 1 ? UserProfile(userId) : ConversationInfo(userId, type),
            type == 1 ? UserPersonalInterfacePage(userInfoEntity: userInfoEntity) : ConversationInfo(userId, type),
      ),
    );
  }

  getConversion() async {
    V2TimValueCallback<V2TimConversation> data = await TencentImSDKPlugin
        .v2TIMManager
        .getConversationManager()
        .getConversation(conversationID: conversationID);
     String _msgID;
     int _type;
     String _groupID;
     String _userID;
    if (data.code == 0) {
      _msgID = data.data.lastMessage == null ? '' : data.data.lastMessage.msgID;
      _type = data.data.type;
      _groupID = data.data.groupID;
      _userID = data.data.userID;
      print("_type $_type");
      print('_userID $_userID');
      print('_groupID $_groupID');
      setState(() {
        type = _type;
        lastMessageId = _msgID;
        groupID = _groupID;
        userID = widget.userId;
        righTopIcon = _type == 1
            ? Icon(
                Icons.account_box,
                color: CommonColors.getWitheColor(),
              )
            : Icon(
                Icons.supervisor_account,
                color: CommonColors.getWitheColor(),
              );
      });
    }

    //判断会话类型，c2c or group

    if (_type == 1) {
      // c2c
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getC2CHistoryMessageList(
            userID: widget.userId == null ? "" : widget.userId,
            count: 100,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          List<V2TimMessage> list = listRes.data;
          if (list.length == 0) {
            print('没有消息啊！！！');
            list = List.empty(growable: true);
          }
          print("conversationID $conversationID 消息数量 ${listRes.data.length}");
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(conversationID, list);
        } else {
          print('conversationID 获取历史消息失败 ${listRes.desc}');
        }
      });
    } else if (_type == 2) {
      // group
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getGroupHistoryMessageList(
            groupID: _groupID == null ? "" : _groupID,
            count: 100,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          print(
              "conversationID listRes.data ${listRes.data.length} $_groupID ");
          List<V2TimMessage> list = listRes.data;
          if (list.length == 0) {
            print('conversationID 没有消息啊！！！');
            list = List.empty(growable: true);
          } else {
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .addMessage(conversationID, list);
          }
          print("conversationID $conversationID 消息数量 ${listRes.data.length}");
        } else {
          print('conversationID 获取历史消息失败');
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Color(0xff2b244d),
      appBar: AppBar(
        title: type == 1 ? infos != null ? Text(infos.data[0].nickName ) :Text('会话') :Text('会话'),
        backgroundColor: Color(0xff140c3d),
        actions: [
          IconButton(
            icon: Icon(
              Icons.account_box,
              color: CommonColors.getWitheColor(),
            ),
            onPressed: () {
              openProfile(context);
            },
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ConversationInner(conversationID, type, widget.userId, groupID),
          ),
          type == 0
              ? Container()
              : MsgInput(type == 1 ? widget.userId : groupID, type),
          Container(
            height: MediaQuery.of(context).padding.bottom,
          )
        ],
      ),
    );
  }

  Future<void> getUserInfo() async {
    widget.userId != null  ?infos =  await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [widget.userId]) :
     groups = await TencentImSDKPlugin
        .v2TIMManager.getGroupManager().getGroupsInfo(groupIDList: [groupID]);
  }

  getUserInfos() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserDetailsByUserIdRequest();
    request.add('userId', widget.userId).add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      userInfoEntity = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
      prefs.setString('USERINFO', jsonEncode(userInfoEntity));
      print(userInfoEntity);
    });
  }
}
